package com.design.movieticket.service.Impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.design.movieticket.common.util.RandomTicketNum;
import com.design.movieticket.dto.CinemaDto;
import com.design.movieticket.entity.Balance;
import com.design.movieticket.entity.Cinema;
import com.design.movieticket.entity.User;
import com.design.movieticket.entity.UserRole;
import com.design.movieticket.mapper.BalanceMapper;
import com.design.movieticket.mapper.CinemaMapper;
import com.design.movieticket.mapper.UserMapper;
import com.design.movieticket.mapper.UserRoleMapper;
import com.design.movieticket.service.CinemaService;
import com.design.movieticket.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

@Service
public class CinemaServiceImpl extends ServiceImpl<CinemaMapper, Cinema> implements CinemaService  {
    @Resource
    private CinemaMapper cinemaMapper;

    @Resource
    private UserRoleMapper userRoleMapper;

    @Resource
    private UserMapper userMapper;

    @Resource
    private UserService userService;

    @Resource
    private BalanceMapper balanceMapper;

    /** 分页查询 */
    @Override
    public LambdaQueryWrapper buildQuery(Cinema cinema,String username,String userRole) {
        LambdaQueryWrapper lambdaQueryWrapper;
        if (userRole.equals("superAdmin")){
            lambdaQueryWrapper = Wrappers.lambdaQuery(Cinema.class)
                    .like(StringUtils.isNotBlank(cinema.getCinemaName()),Cinema::getCinemaName,cinema.getCinemaName())
                    .like(StringUtils.isNotBlank(cinema.getAddress()),Cinema::getAddress,cinema.getAddress())
                    .like(StringUtils.isNotBlank(cinema.getPrincipal()),Cinema::getPrincipal,cinema.getPrincipal());
        }else{
            lambdaQueryWrapper = Wrappers.lambdaQuery(Cinema.class)
                    .like(StringUtils.isNotBlank(cinema.getCinemaName()),Cinema::getCinemaName,cinema.getCinemaName())
                    .like(StringUtils.isNotBlank(cinema.getAddress()),Cinema::getAddress,cinema.getAddress())
                    .like(StringUtils.isNotBlank(cinema.getPrincipal()),Cinema::getPrincipal,cinema.getPrincipal())
                    .eq(Cinema::getAdmin,username);
        }
        return lambdaQueryWrapper;
    }

    /** 分页相关 */
    @Override
    public <E extends IPage<Cinema>> E page(E page, Wrapper<Cinema> queryWrapper) {
        return super.page(page, queryWrapper);
    }

    /** 新增或更新影院数据 */
    @Override
    public void addOrUpdateCinemaInfo(Cinema cinema) {
        if (cinema.getCinemaNumber().equals("")){
            cinema.setCinemaNumber(RandomTicketNum.createCinemaNum());
        }
        if (cinemaMapper.selectOne(new LambdaQueryWrapper<Cinema>().eq(Cinema::getPrincipal,cinema.getPrincipal()))==null){
            User user = new User();
            user.setPassword(new BCryptPasswordEncoder().encode("123456"));
            user.setStatus(1);
            user.setUsername(cinema.getPrincipal());
            user.setLevel("黄金");
            userMapper.insert(user);

            User user1 = userService.getUserInfoByUsername(cinema.getPrincipal()); //获取新建用户信息
            Long userId = user1.getId();


            UserRole userRole = new UserRole();  //为新用户创建对应角色id
            userRole.setRoleId(3L);
            userRole.setUserId(userId);
            userRoleMapper.insert(userRole);

            Balance balance = new Balance(); //为新用户创建余额信息
            balance.setBalance(new BigDecimal(0));
            balance.setPoints(new BigDecimal(0));
            balance.setUsername(user1.getUsername());
            balance.setUserId(userId);
            balanceMapper.insert(balance);
        }
        super.saveOrUpdate(cinema);
    }

    /** 获取影院信息详情 */
    @Override
    public Cinema getCinemaDetail(long id) {
        return super.getById(id);
    }

    /** 删除影院信息 */
    @Override
    public void delCinemaById(long id) {
        super.removeById(id);
    }

    /** 根据登录用户获取影院id */
    @Override
    public Cinema getCinemaId(String loginUser) {
        return cinemaMapper.selectOne(new LambdaQueryWrapper<Cinema>().eq(Cinema::getPrincipal,loginUser));
    }

    @Override
    public List<String> getAdmin() {
        return cinemaMapper.getAdmin();
    }

    @Override
    public List<CinemaDto> wxGetCinemaList(String movieName, String selectDay) {
        String dayStart = null;
        String dayEnd = null;
        Date nowTime = new Date();
        List<CinemaDto> cinemaDtoList = null;
        if (movieName == null){
            cinemaDtoList = cinemaMapper.wxGetCinemaList();
        }else{
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                String tar = format1.format(nowTime);
                Date date1 = format.parse(selectDay);
                dayStart = format.format(date1);
                dayEnd = dayStart +' '+'2'+'3'+':'+'5'+'9'+':'+'5'+'9';
                if (tar.substring(8,10).equals(dayStart.substring(8,10))){
                    dayStart = dayStart +' '+ tar.substring(11,19);
                }else{
                    dayStart = dayStart +' '+'0'+'0'+':'+'0'+'0'+':'+'0'+'0';
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }
            cinemaDtoList = cinemaMapper.wxGetCinemaListEqualsMovieId(movieName,dayStart,dayEnd);
        }
        return cinemaDtoList;
    }
}
